﻿#include "../../beans/headers/TextItem.h"
#include <QTextDocument>
#include <QTextOption>
#include <QDebug>

TextItem::TextItem(QGraphicsItem *parent):QGraphicsTextItem(parent)
{
    this->setData(ITEM_CLASS,EnumType::ItemClass_TextItem);
    this->setZValue(-1);

    this->ensureVisible();
}

QRectF TextItem::boundingRect(void) const
{
    // 设置Item的矩形默认大小
    return QRectF(0,0,m_Width,m_Height);
}

QPainterPath TextItem::shape(void) const
{
    QPainterPath path;
    path.addRect(boundingRect());
    return path;
}

// 获取焦点事件
void TextItem::focusInEvent(QFocusEvent *event)
{
    qDebug()<<"TextItem::focusInEvent";
    // 文本框获取焦点后，鼠标样式设置为“工”字型
    this->setCursor(Qt::IBeamCursor);

    // 获取焦点，设置为可编辑状态
    this->setTextInteractionFlags(Qt::TextEditorInteraction);
    QGraphicsTextItem::focusInEvent(event);
}

// 失去焦点事件
void TextItem::focusOutEvent(QFocusEvent *event)
{
    qDebug()<<"TextItem::focusOutEvent";

    // 恢复不能编辑状态
    this->setTextInteractionFlags(Qt::NoTextInteraction);

    // 设置不可被选择
    this->setFlags(flags()&~ItemIsSelectable);

    // 给父部件发射已经修改的信号，使其textItem在父部件中自动居中
    emit signal_Edited();
    this->clearFocus();

    // 文本框失去焦点后，鼠标样式设置“十”字型
    this->setCursor(Qt::SizeAllCursor);
    QGraphicsTextItem::focusOutEvent(event);
}

// 按键事件（点击回车失去焦点）
void TextItem::keyPressEvent(QKeyEvent *event)
{
    qDebug()<<"TextItem::keyPressEvent";
    if(event->key() == Qt::Key_Return||event->key() == Qt::Key_Enter)
    {
        // 点击回车失去焦点
        this->clearFocus();
        this->setFlags(flags()&~ItemIsSelectable);
    }else{
        QGraphicsTextItem::keyPressEvent(event);
    }
}

qreal TextItem::Height() const
{
    return m_Height;
}

void TextItem::setHeight(const qreal &Height)
{
    m_Height = Height;
}

qreal TextItem::Width() const
{
    return m_Width;
}

void TextItem::setWidth(const qreal &Width)
{
    m_Width = Width;
}
